<script lang="ts" setup>
import { getActivityDetailsApi, getJoinApi, getReceiveApi } from '@/services/my'
import { computed, nextTick, ref, inject } from 'vue'
import { useMemberStore, usePhoneStore, useLocationStore } from '@/stores'
import rulesPopup from './components/rulesPopup.vue'
import { PageSkip, Toast } from '@/utils/tools'
import { onLoad, onShow } from '@dcloudio/uni-app'
const { loginPromise } = <{ loginPromise: Promise<unknown> }>inject('globalData')

const show = ref(false) // 防止页面滚动穿透
const rulesPopupRef = ref()
const locationStore = useLocationStore()
const phoneStore = usePhoneStore()
const memberStore = useMemberStore()
const { bottom = 0 } = phoneStore.phoneInfo ?? {}
const accumulated = ref(0)

const bgcImg = ref('')
const list = ref<any[]>([])
const rewardsList = ref<any[]>([])
const rowImage = computed(() => {
  const num = Math.min(Math.ceil(list.value.length / 4), 3)
  return ``
})
const iconPng = ref<any[]>([])
const getButton = ref({
  text: '',
  bgc: '',
  buttonStatus: 0,
})
const status = ref<number | null>(null)
const activitySignInsId = ref<string | null>(null)
const popupData = ref({
  popupImageUrl: '',
  title: '确定',
})

const rules = ref('')
/**点击领取 */
function participation() {
  switch (getButton.value.buttonStatus) {
    case 2:
      getJoin()
      return
    case 4:
      getReceive()
      return
    default:
      SkipPopupRef.value.close()
  }
}

const SkipPopupRef = ref()

// 调用小程序的分享，以及监听小程序分享
// import useMiniShare from '@/hooks/useMiniShare'
// const { isShareFriends, setupOnShareAppMessage, onShareAppMessage } = useMiniShare()

// isShareFriends()
// onShareAppMessage
/** 处理展示按钮样式 */
function handleStyle() {
  // [1:立即参与灰、2:立即参与、3:立即领取灰、4:立即领取、5:恭喜完成全部打卡灰]
  if (status.value !== 1) {
    // 状态:[0:删除,1:进行中,2:已失效,3:已过期,4:待开始]
    return '#D6D6D6'
  }
  switch (getButton.value.buttonStatus) {
    case 1:
      return '#D6D6D6'
    case 2:
      return 'linear-gradient(91deg, #95F151 0.53%, #8ADF4B 95.18%)'
    case 3:
      return '#D6D6D6'
    case 4:
      return 'linear-gradient(91deg, #95F151 0.53%, #8ADF4B 95.18%)'
    case 5:
      return '#D6D6D6'
  }
}

/** 处理展示按钮文字*/
function handleText() {
  if (status.value !== 1) {
    // 状态:[0:删除,1:进行中,2:已失效,3:已过期,4:待开始]
    return '活动已结束'
  }
  // [1:立即参与灰、2:立即参与、3:立即领取灰、4:立即领取、5:恭喜完成全部打卡灰]
  switch (getButton.value.buttonStatus) {
    case 1:
      return getButton.value.text
    case 2:
      return getButton.value.text
    case 3:
      return '立即领取'
    case 4:
      return '立即领取'
    case 5:
      return '恭喜完成全部打卡'
  }
}
/**处理展示图片 */
function handleSrc(i: any) {
  if (i.rewardImageUrl) {
    return i.rewardImageUrl
  } else if (accumulated.value >= i.id) {
    return iconPng.value[1]
  } else if (accumulated.value < i.id) {
    return iconPng.value[0]
  }
}
/**处理没有打卡的日期 */
function handleNo(i: any) {
  if (i.rewardImageUrl) {
    return false
  } else if (accumulated.value >= i.id) {
    return false
  } else if (accumulated.value < i.id) {
    return true
  }
}
/**处理打卡以及未打卡的日历整体颜色 */
function handleFilter(i: any) {
  if (i.isReceive) {
    return 'grayscale(0%)'
  } else if (accumulated.value >= i.id) {
    return 'grayscale(0%)'
  } else if (accumulated.value < i.id && i.rewardImageUrl) {
    return 'grayscale(100%)'
  }
}
/**处理日历背景色 */
function handleBgc(i: any) {
  if (i.isReceive) {
    return '#F1FFE6'
  } else if (accumulated.value >= i.id) {
    return '#F1FFE6'
  } else if (accumulated.value < i.id && i.rewardImageUrl) {
    return '#F3F3F3'
  }
}
/**已领取icon展示 */
function handleReceive(i: any) {
  return i.isReceive
}
/**初始化展示日历 */
function initList(arrList: any[]) {
  if (arrList.length) {
    let maxVal = 0
    // 过滤
    const filteredData = arrList.filter((item) => item?.rules)
    if (filteredData.length === 0) {
      return []
    }
    // 获取最大单
    maxVal = Math.max(...filteredData.map((item) => item?.rules))
    // 生成数组
    const arr = Array.from({ length: maxVal }, (_, i) => ({
      rewardImageUrl: null,
      isReceive: null,
      id: i + 1,
    }))
    // 循环替换用户是否已经领取的状态
    arrList.find((i) => {
      arr.forEach((e) => {
        if (i.rules === e.id) {
          e.isReceive = i.isReceive
          e.rewardImageUrl = i.rewardImageUrl
        }
      })
    })
    console.log({ arr })
    return arr
  }
}
function initData(data: any) {
  activitySignInsId.value = data?.id
  status.value = data?.status
  rules.value = data?.activityRule
  getButton.value.text = data?.buttonName
  getButton.value.buttonStatus = data?.buttonStatus
  bgcImg.value = data?.backgroundImg
  accumulated.value = data?.checkedCount
  rewardsList.value = data?.activitySignInsRulesVOList
  iconPng.value = [data?.uncheckedIcon, data?.checkedIcon]
  list.value = initList(data?.activitySignInsRulesVOList) as any
  // const shareParams = {
  //   path: `/pagesMy/checkIn/checkIn?activitySignInsId=${activitySignInsId.value}`,
  //   title: data?.shareTitle,
  //   imageUrl: data?.shareImg,
  // }
  // setupOnShareAppMessage(shareParams)
}
/**获取活动详情 */
async function getActivityDetails() {
  try {
    const res = await getActivityDetailsApi({
      activitySignInsId: activitySignInsId.value,
      cityName: locationStore.location?.cityName,
    })
    if (res.code === 200 && res.data) {
      initData(res.data)
    }
  } catch (error) {}
}
/**触发领取奖励 */
function getReceive() {
  getReceiveApi({
    activitySignInsId: activitySignInsId.value,
  })
    .then((res) => {
      console.log(res)
      if (res.code === 200 && res.data) {
        popupData.value.popupImageUrl = res.data.popupImageUrl
        SkipPopupRef.value.open()
        getActivityDetails()
      } else {
        Toast('当前活动过于火爆\n领取失败！')
      }
    })
    .catch(() => {})
}
/**触发参与活动 */
function getJoin() {
  getJoinApi({
    activitySignInsId: activitySignInsId.value,
  })
    .then((res) => {
      console.log(res)
      if (res.code === 200) {
        Toast('参与成功，快去打卡吧！')
        getActivityDetails()
      }
    })
    .catch(() => {})
}
/**打开规则弹窗 */
async function handleOpenRules() {
  if (!memberStore.token) {
    await nextTick()
    popupRef.value?.open()
    return
  }
  rulesPopupRef.value?.open()
}
/**跳转兑换记录页面 */
async function handleExchangeRecord() {
  if (!memberStore.token) {
    await nextTick()
    popupRef.value?.open()
    return
  }
  PageSkip(`/pagesMy/checkIn/exchangeRecord?activitySignInsId=${activitySignInsId.value}`)
}
const popupRef = ref()
onShow(() => {
  uni.showLoading({
    title: '加载中',
    mask: true,
  })
  loginPromise
    .then(() => {
      if (memberStore.token) {
        getActivityDetails().finally(() => {
          uni.hideLoading()
        })
      }
    })
    .catch(() => {
      uni.hideLoading()
    })
})

onLoad(async (e: any) => {
  console.log('onLoad', e)
  activitySignInsId.value = e.activitySignInsId ? e.activitySignInsId : ''
  if (!memberStore.token) {
    await nextTick()
    popupRef.value?.open()
  }
})
</script>
<template>
  <!-- 防止页面滚动穿透 -->
  <page-meta :page-style="'overflow:' + (show ? 'hidden' : 'visible')"></page-meta>

  <view class="checkInBox">
    <!-- 头部导航栏 -->
    <BjsNavBar title="吃饭打卡" backUrl="/pages/index/index" />
    <!-- 背景图片 -->
    <image class="bgcImg" :src="bgcImg" mode="scaleToFill" />
    <view class="rules" @tap="handleOpenRules()">规则</view>
    <view class="exChange" @tap="handleExchangeRecord()">兑换记录</view>
    <!-- 打卡日历 -->
    <view class="checkInCalendar">
      <image :src="rowImage" mode="widthFix" />
      <view class="accumulated"
        >已累计打卡 <text class="accumulatedNum">{{ accumulated ?? 0 }}</text> 单
      </view>
      <view class="checkInImgList">
        <view
          class="imgItem"
          :style="{ filter: handleFilter(i), background: handleBgc(i) }"
          v-for="i in list"
          :key="i.id"
          @tap=""
        >
          <image class="_img" :src="handleSrc(i)" mode="scaleToFill" />
          <image
            class="icon_9"
            v-show="handleReceive(i)"
            src="/static/images/icon_9.png"
            mode="scaleToFill"
          />
          <text class="_No" v-show="handleNo(i)">{{ i.id }}</text>
        </view>
      </view>

      <button
        class="getButton"
        @tap.stop="participation()"
        :style="{ background: `${handleStyle()}` }"
      >
        {{ handleText() }}
      </button>
    </view>
    <!-- 打卡奖励 -->
    <view class="scroll_viewBox">
      <scroll-view class="scroll_view" scroll-x>
        <view class="_item" v-for="i in rewardsList" :key="i.id">
          <image class="itemImg" :src="i.rewardImageUrl" mode="scaleToFill" />
          <image
            v-if="i.isReceive"
            class="successfulPng"
            src="/static/images/successfulPng.png"
            mode="scaleToFill"
          />
          <view class="itemName">{{ i.rewardName }} </view>
        </view>
      </scroll-view>
    </view>

    <rulesPopup ref="rulesPopupRef" :rules="rules" @changeVal="(val) => (show = val)" />

    <BjsPopup ref="popupRef" />
    <BjsSkipPopup
      :img="popupData.popupImageUrl"
      :buttonText="popupData.title"
      ref="SkipPopupRef"
      @receive="participation"
    />
  </view>
</template>
<style lang="scss" scoped>
.checkInBox {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f6f6f6;
  .bgcImg {
    width: 100vw;
    height: 974rpx;
    position: relative;
  }
  .checkInCalendar {
    width: 716rpx;
    min-height: 514rpx;
    transform: translateY(-400rpx);
    position: relative;
    z-index: 2;
    .accumulated {
      position: absolute;
      top: 116rpx;
      left: 62rpx;
      color: #666;
      font-family: 'PingFang SC';
      font-size: 28rpx;
      .accumulatedNum {
        color: #8adf4b;
      }
    }
    .checkInImgList {
      position: absolute;
      top: 170rpx;
      left: 48rpx;
      // filter: grayscale(100%);
      display: flex;
      flex-wrap: wrap;
      .imgItem {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 140rpx;
        height: 164rpx;
        border-radius: 52rpx;
        background: #f3f3f3;
        margin: 0 20rpx 20rpx 0;
        ._img {
          width: 116rpx;
          height: 84rpx;
        }
        .icon_9 {
          position: absolute;
          top: 12rpx;
          left: 6rpx;
          width: 128rpx;
          height: 128rpx;
          z-index: 9;
        }
        ._No {
          position: absolute;
          top: 54%;
          left: 50%;
          transform: translate(-50%, -50%);
          color: #fff;
          font-family: 'PingFang SC';
          font-size: 40rpx;
        }
        &:nth-child(4n) {
          margin: 0;
        }
      }
    }
    .getButton {
      position: absolute;
      bottom: 66rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 616rpx;
      height: 88rpx;
      line-height: 88rpx;
      background: v-bind('getButton.bgc');
      border-radius: 22px;
      // box-shadow: 0rpx 10rpx 12rpx 0rpx #d8ffbb;
      color: #fff;
      text-align: center;
      font-family: 'PingFang SC';
      font-size: 30rpx;
    }
  }
  .scroll_viewBox {
    margin-top: 26rpx;
    width: 692rpx;
    height: 366rpx;
    border-radius: 20rpx;
    background: #fff;
    transform: translateY(-400rpx);
    background-image: url('');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-position: center;
    z-index: 2;
    .scroll_view {
      margin-top: 132rpx;
      height: 274rpx;
      white-space: nowrap;
      ._item {
        display: inline-block;
        width: 204rpx;
        min-height: 224rpx;
        margin: 0 40rpx 0 0;
        position: relative;
        .itemImg {
          width: 100%;
          height: 148rpx;
        }
        .successfulPng {
          position: absolute;
          right: 0rpx;
          top: 0rpx;
          width: 48rpx;
          height: 48rpx;
          z-index: 9;
        }
        .itemName {
          width: 100%;
          color: #000;
          text-align: center;
          font-family: 'PingFang SC';
          font-size: 28rpx;
          margin-top: 16rpx;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
        }
        &:last-child {
          margin: 0 40rpx 0 0;
        }
        &:first-child {
          margin: 0 40rpx 0 40rpx;
        }
      }
    }
  }
  .rules,
  .exChange {
    position: absolute;
    right: 0rpx;
    top: 0rpx;
    color: #fff;
    font-family: 'PingFang SC';
    font-size: 24rpx;
    border-radius: 12rpx 0rpx 0rpx 12rpx;
    opacity: 0.4;
    background: #000;
    z-index: 2;
  }
  .rules {
    top: v-bind('`${bottom + 23}px`');
    width: 76rpx;
    height: 44rpx;
    line-height: 44rpx;
    text-align: center;
  }
  .exChange {
    top: v-bind('`${bottom + 53}px`');
    width: 76rpx;
    height: 84rpx;
    padding: 10rpx 12rpx;
  }
}
</style>
